package com.xnyy.lottery.controller;

import com.xnyy.lottery.common.CommonResult;
import com.xnyy.lottery.common.exception.CustomException;
import com.xnyy.lottery.domain.dto.DataDTO;
import com.xnyy.lottery.domain.dto.RegisterQueryDTO;
import com.xnyy.lottery.domain.entity.RegisterRecord;
import com.xnyy.lottery.domain.vo.MemberRegisterParkingInfoVO;
import com.xnyy.lottery.service.RegisterService;
import com.xnyy.lottery.service.TicketService;
import com.xnyy.lottery.util.LocalCache;
import com.xnyy.lottery.util.PrintUtils;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @description: 登记服务
 * @auther: Administrator
 * @date: 2022/9/17 01:42
 */
@AllArgsConstructor
@RestController
@RequestMapping("/register")
public class RegisterController extends BaseController {

    private final RegisterService registerService;
    private final TicketService ticketService;

    @GetMapping("/list")
    public CommonResult list(RegisterQueryDTO dto) {
        startPage();
        List<MemberRegisterParkingInfoVO> list = registerService.selectList(dto);
        return getDataTable(list);
    }

    @GetMapping("/get")
    public CommonResult get(@RequestParam("id") Long id) {
        return CommonResult.success(registerService.getRegisterParkingInfo(id));
    }

    public static final String REPEAT_SUBMIT_KEY = "repeat_submit:";

    @PostMapping("/add")
    public CommonResult register(@RequestBody RegisterRecord registerRecord) {
        final Object o = LocalCache.get(REPEAT_SUBMIT_KEY);
        if (o != null) {
            throw new CustomException("您已经请求取号，动作不要太快了");
        }
        LocalCache.set(REPEAT_SUBMIT_KEY, "1", 1000);
        
        return CommonResult.success(registerService.register(registerRecord));
    }

    @PostMapping("/givup")
    public CommonResult givup(@RequestBody RegisterRecord registerRecord) {
        registerService.givup(registerRecord.getBarCode());
        return CommonResult.success();
    }

    /**
     * 打印
     *
     * @param id 登记ID
     */
    @PostMapping("/print")
    public CommonResult print(@RequestParam(value = "id") String id) {
        MemberRegisterParkingInfoVO registerParkingInfo = registerService.getByBarCode(id);
        if (registerParkingInfo == null) {
            registerParkingInfo = registerService.getRegisterParkingInfo(Long.parseLong(id));
        }
        //打印工具
        Integer type = registerParkingInfo.getResult() == 1 ? 2 : 1;
        PrintUtils.print(registerParkingInfo, type);
        return CommonResult.success("打印成功");
    }

}
